﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：UserValidateFilterAttribute.cs
// 功能描述：TongTongMall.MallWeb
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http.Controllers;
using TongTongMall.Dependecy;
using TongTongMall.MallWeb.Application.Configuration.Session;
using TongTongMall.MallWeb.Application.Users;
using TongTongMall.MallWeb.Core.Identitys;
using TongTongMall.Oauth2._0.Client;
using TongTongMall.Oauth2._0.Client.Attributes;
using TongTongMall.Oauth2._0.Models;
using TongTongMall.Redis.Cache;
using TongTongMall.Runtime.Session;
using TongTongMall.Threading;

namespace TongTongMall.MallWeb.WebApi.Filter
{
    /// <summary>
    /// 
    /// </summary>
    public class UserValidateFilterAttribute : OAuthAttribute
    {
        public new IMallWebSession Session { get; private set; }

        public UserValidateFilterAttribute(IMallWebSession session)
        {
            Session = session;
        }

        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var isAuthorized = base.IsAuthorized(actionContext);
            if (isAuthorized)
            {
                Dictionary<OAuthClientErrorStatus, string> errorStatusDic = new Dictionary<OAuthClientErrorStatus, string>();
                //判断用户信息是否发生变化
                var userService = IocManager.Instance.Resolve<UserRedisManager>();
                var userCacheKey = RedisKeys.Instance.UserAuthorizationAfterRedisKey(Session.TenantName, Session.UserID.ToString(), Session.Platform);
                var oauthUser = AsyncHelper.RunSync(() => { return userService.GetUserInfo<OAuthRedisUser>(userCacheKey); });
                if (oauthUser == null)
                {
                    errorStatusDic.Add(OAuthClientErrorStatus.UserLack, "没有检测到用户信息");
                }
                else if (oauthUser.TicketVersion != Session.TicketVersion)
                {
                    errorStatusDic.Add(OAuthClientErrorStatus.UserChange, "用户信息发生变化");
                }
                if (OnValidateAuthorzation != null && errorStatusDic.Count > 0)
                {
                    OnValidateAuthorzation.Invoke(actionContext, errorStatusDic);
                }
                else
                {
                    if (errorStatusDic.Count > 0)
                    {
                        actionContext.Response = new AuthenticationFailureMessage(HttpStatusCode.Unauthorized, actionContext.Request,
                            new
                            {
                                error = errorStatusDic.FirstOrDefault().Key,
                                error_message = errorStatusDic.FirstOrDefault().Value
                            });
                    }
                }
            }
            return isAuthorized;
        }
    }
}